package webService;


import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import serverDB.Client;
import serverDB.ConnectToDataBase;

/**
 * check if the client is already exist
 * @author ran, barak
 *
 */
public class isClientExistServlet  extends HttpServlet{
	/**
	 * Default serialVersionUID
	 */
	private static final long serialVersionUID = 1L;
	/**
	 * get the post request
	 */
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// if the user is exist
		if(checkUser(req, resp))
			resp.sendRedirect(resp.encodeRedirectURL("logedIn2.jsp"));
		else
			resp.sendRedirect(resp.encodeRedirectURL("index.jsp"));
	}
	
	/**
	 * get the Get request
	 */
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// get the output stream
		ObjectOutputStream outputStream = new ObjectOutputStream(resp.getOutputStream());
		// if the user is alresdy exist
		if(checkUser(req, resp))
			outputStream.writeObject(true);
		else
			outputStream.writeObject(false);
		outputStream.close();
	}
	
	/**
	 * check if the user exist
	 * @param req the HttpServletRequest
	 * @param resp the HttpServletResponse
	 * @return true if the user exists
	 */
	private boolean checkUser(HttpServletRequest req, HttpServletResponse resp){
		// get the session 
		HttpSession session = req.getSession();
		ConnectToDataBase connectToDataBase = ConnectToDataBase.getInst();
		// get the client
		List<Client> list=connectToDataBase.getClient2("from Client where user_name= '"+req.getParameter("userName")+"' and password= '"+req.getParameter("pass")+"'");
		if(list!=null){
			// get the parameters
			session.setAttribute("userName", req.getParameter("user" +"Name"));
			session.setAttribute("logedIn", true);
			session.setAttribute("boxesList", list.get(0).getBoxes());
			// set cookies
			if(req.getParameter("remember")!=null){
				Cookie cookie = new Cookie ("cleverDropBoxCookie",req.getParameter("userName"));
				cookie.setMaxAge(365 * 24 * 60 * 60);
				resp.addCookie(cookie);
			}
			return true;			
		}
		// if the client isn't exist
		else{
			session.setAttribute("logedIn", false);
			session.setAttribute("error", "userName or password was incorect!");
			return false;
			
		}
	}
}
